package com.zengdada.authority.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zengdada.authority.annotation.SysLog;
import com.zengdada.authority.annotation.SysLogType;
import com.zengdada.authority.config.security.intercept.AuthorityUtil;
import com.zengdada.authority.exception.RoutineException;
import com.zengdada.authority.mapper.AppUserMapper;
import com.zengdada.authority.model.AppUser;
import com.zengdada.authority.service.AppUserAuthorityService;
import com.zengdada.authority.service.EnhanceBaseService;
import com.zengdada.authority.utils.Base64Util;
import com.zengdada.authority.utils.CommonUtils;
import com.zengdada.authority.utils.HEXUtil;
import com.zengdada.authority.utils.mapper.Page;
import com.zengdada.authority.utils.mapper.Sort;
import com.zengdada.authority.utils.where.MapperWhere;
import com.zengdada.authority.utils.where.Where;
import com.zengdada.authority.utils.where.result.MapperAnalysisResultMerge;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AppUserAuthorityServiceImpl extends EnhanceBaseService<AppUser> implements AppUserAuthorityService {

    @Autowired
    AuthorityUtil authorityUtil;

    @Override
    @SysLog(value = "登录", type = SysLogType.SERVICE)
    public AppUser login(AppUser user) {
        if (StringUtils.isBlank(user.getAccount()))
            throw new RoutineException("账号不能为空");
        if (StringUtils.isBlank(user.getPassword()))
            throw new RoutineException("密码不能为空");
        List<AppUser> list = mapper.selectByExample(new Example.Builder(AppUser.class)
                .where(WeekendSqls.<AppUser>custom().andEqualTo(AppUser::getAccount, user.getAccount()).andEqualTo(AppUser::getState, 1)).build());
        if (list.size() == 0) {
            //账号不存在
            throw new RoutineException("账号不存在");
        }
        String testPassword = HEXUtil.stringHEX(String.format("%s %s", list.get(0).getId(), user.getPassword()), HEXUtil.Type.MD5);
        if (!testPassword.equals(list.get(0).getPassword())) {
            //密码错误
            throw new RoutineException("密码错误");
        }
        return list.get(0);
    }

    @Override
    @SysLog(value = "修改密码", type = SysLogType.SERVICE)
    public void changPassword(AppUser user, String oldPassword, String password, String confirmPassword) {
        if (StringUtils.isBlank(password)) throw new RoutineException("新密码不能为空！");
        if (!password.equals(confirmPassword)) throw new RoutineException("两次密码不一致！");
        oldPassword = Base64Util.decodeBase64(oldPassword, 2);
        password = Base64Util.decodeBase64(password, 2);
        String hex = HEXUtil.stringHEX(String.format("%s %s", user.getId(), oldPassword), HEXUtil.Type.MD5);
        if (!user.getPassword().equals(hex)) throw new RoutineException("原密码错误！");
        AppUser newUser = new AppUser();
        newUser.setPassword(HEXUtil.stringHEX(String.format("%s %s", user.getId(), password), HEXUtil.Type.MD5));
        if (0 == mapper.updateByExampleSelective(newUser, new Example.Builder(AppUser.class)
                .where(WeekendSqls.<AppUser>custom().andEqualTo(AppUser::getId, user.getId()).andEqualTo(AppUser::getPassword, hex)).build()))
            throw new RoutineException("没有任何修改");

    }


    @Override
    public PageInfo<AppUser> selectPageInfoByRoleId(String roleId, boolean isIn, String searchs, Page page, Sort sort) {
        Where where = null;
        try {
            if (!StringUtils.isEmpty(searchs)) {
                where = Where.formJsonString((StringEscapeUtils.unescapeHtml4(searchs)));
            }
        } catch (Exception e) {
            throw new RoutineException("查询条件解析失败：" + e.getMessage());
        }
        MapperAnalysisResultMerge analysis = new MapperAnalysisResultMerge();
        if (where != null) {
            analysis = JSON.parseObject(JSON.toJSONString(where), MapperWhere.class).setFields(columns).analysisMerge();
        }
        if (page != null) {
            PageHelper.startPage(page.getPage(), page.getPageSize());
        }
        List<Map<String, Object>> list = ((AppUserMapper) mapper).selectUsersByRoleId(isIn, String.valueOf(roleId), analysis, sort != null && sort.isNotNull() ? sort : null);
        PageInfo<Map<String, Object>> temp = new PageInfo<>(list);
        List<AppUser> appUserList = JSON.parseArray(JSON.toJSONString(CommonUtils.depthTransformHumpNew(list)), AppUser.class);
        return new PageInfo<AppUser>(appUserList) {{
            setTotal(temp.getTotal());
        }};
    }


    @Override
    @SysLog(value = "创建新用户", type = SysLogType.SERVICE)
    public int add(AppUser user) {
        AppUser loginUser = authorityUtil.getLoginUser();
        user.setId(null);
        user.setCreateUser(loginUser.getId());
        mapper.insertSelective(user);
        AppUser appUser = new AppUser();
        appUser.setId(user.getId());
        appUser.setPassword(HEXUtil.stringHEX(String.format("%s %s", user.getId(), user.getPassword()), HEXUtil.Type.MD5));
        mapper.updateByPrimaryKeySelective(appUser);
        return 1;
    }

    @Override
    @SysLog(value = "修改用户", type = SysLogType.SERVICE)
    public int updateById(AppUser user) {
        AppUser loginUser = authorityUtil.getLoginUser();
        AppUser old = selectById(user.getId());
        if (old == null) throw new RoutineException("该用户不存在！！");
        if (old.getPassword().equals(user.getPassword()))
            user.setPassword(null);
        else
            user.setPassword(HEXUtil.stringHEX(String.format("%s %s", user.getId(), user.getPassword()), HEXUtil.Type.MD5));
        user.setModifiedUser(loginUser.getId());
        user.setModifiedTime(new Date());
        mapper.updateByPrimaryKeySelective(user);
        return 1;
    }
}
